package com.quark.framework.i18n;

import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;

import com.quark.framework.utility.QuarkLog;
import com.quark.framework.utility.QuarkUtilFileReader;

public class QuarkI18nTextProvider {
	private Map<String, String> transData = new HashMap<String, String>();
	
	public void set(String key, String value)
	{
		transData.put(key, value);
	}
	
	public int loadFromFile(String fileName)
	{
		String content = QuarkUtilFileReader.readAllString(fileName);
		if (content == null || content == "")
		{
			QuarkLog.logError("I18n Load From File: File Content Null!");
			return -1;
		}
		try
		{
			JSON json = JSONSerializer.toJSON(content);
			if(json.getClass().equals(JSONObject.class))
				//accept only jsonobject
			{
				JSONObject object = (JSONObject)json;
				if(object.isEmpty())
					return 0;
				JSONArray array = object.names();
				for(int i = 0; i < array.size(); i ++)
				{
					set(array.getString(i), object.getString(array.getString(i)));
				}
				return array.size();
			}
			return -1;
		}
		catch(Exception e)
		{
			QuarkLog.log(e);
			return -1;
		}
	}
	
	public String get(String key)
	{
		if(transData.containsKey(key))
		{
			return transData.get(key);
		}
		QuarkLog.logError("I18n: No key " + key + " Found!");
		return key;
	}
}
